import json
import random
import re

from django.db.models import Q
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView

from user.models import UserModel
from user.userser import UserSerializer
from utils.jwttool import tooljwt
from utils.myredis import redis_toll
from utils.sendmsg import send_message

from .tasks import add, send
from utils.authorization import MyAuthentication


# Create your views here.

class LoginPwd(APIView):
    def post(self, request):
        # api = TencentCloudAPI()
        # result = api.captcha(
        #     request.data.get("ticket"),
        #     request.data.get("randstr"),
        #     request._request.META.get("REMOTE_ADDR"),
        # )
        # if result == False:
        #     return Response({"code": 400, "message": "验证码错误"})
        account = request.data.get('account')
        password = request.data.get('password')
        info = UserModel.objects.filter(Q(phone=account) | Q(username=account) | Q(email=account)).first()
        if info is None:
            return Response({"code": 400, "message": "账号不存在"})
        elif info.password == password:
            data = {
                "id": info.id,
                "account": account,
                "head_img": info.head_img,
                "token": tooljwt.getToken(info.id, account)
            }
            if info.head_img:
                data["head_img"] = info.head_img
            else:
                data["head_img"] = "/uploads/img/坤坤2.png"
            return Response({"code": 200, "message": "登录成功", "data": data})
        else:
            return Response({"code": 400, "message": "密码错误"})


class SendCode(APIView):
    def post(self, request):
        phone = request.data.get('phone')
        code = str(random.randint(1000, 9999))
        redis_code = redis_toll.get_str(phone)
        if redis_code:
            return Response({"code": 400, "message": "请勿重复发送", })
        else:
            send.delay(phone, code)
            redis_toll.set_str(phone, code, 60 * 2)
            return Response({"code": 200, "message": "发送成功", })


class Login(APIView):
    def post(self, request):
        account = request.data.get('account')
        code = request.data.get('code')
        redis_code = redis_toll.get_str(account)
        if code != redis_code:
            return Response({'redis_code': redis_code, 'code': code})
        info = UserModel.objects.filter(phone=account, is_show=True).first()
        if info is None:
            new_data = UserModel.objects.create(phone=account)
            token = tooljwt.getToken(new_data.id, new_data.phone)
            id = new_data.id
            return Response(
                {"code": 200, "message": "登录成功", "data": {'token': token, 'id': id, "account": account}})
        token = tooljwt.getToken(info.id, info.phone)
        id = info.id
        return Response({"code": 200, "message": "登录成功", "data": {'token': token, 'id': id, "account": account}})


class Register(APIView):
    def post(self, request):
        account = request.data.get('account')
        password = request.data.get('password')
        re_phone = re.match(r'^1[3-9]\d{9}$', account)
        re_email = re.match(r'^[0-9a-zA-Z_]{6,14}@(qq|sian|163|139)\.com$', account)
        reg_code = request.data.get('reg_code')
        data = {}
        if re_phone:
            code = redis_toll.get_str(account)
            if reg_code is None or reg_code == "":
                return Response({"code": 400, "message": "验证码不能为空"})
            if code != reg_code:
                return Response({"code": 400, "message": "验证码错误"})
            data["phone"] = account
        elif re_email:
            data["email"] = account
        else:
            data["username"] = account
        data["password"] = password
        ser = UserSerializer(data=data)
        if ser.is_valid():
            ser.save()
            return Response({"code": 200, "message": "注册成功", "data": ser.data})
        return Response({"code": 400, "message": "注册失败", "data": ser.errors})


class CheckPhone(APIView):
    def get(self, request):
        phone = request.query_params.get('phone')
        info = UserModel.objects.filter(phone=phone, is_show=1).first()
        if info:
            return Response({"code": 400, "message": "手机号不可用"})
        else:
            return Response({"code": 200, "message": "该手机号可用"})


class TestUser(APIView):
    def post(self, request):
        sum_ = add.delay(1, 2)  # 异步任务的调用  通过delay
        print(sum_.get())
        return Response({"code": 200, "message": "测试成功"})


class Cart(APIView):
    authentication_classes = [MyAuthentication]

    def get(self, request):
        return Response({"code": 200, "message": "购物车"})
